#!/bin/bash
set -e

echo "=== 自定义 TWRP 仓库配置 ==="
read -p "请输入 GitHub 仓库地址 (例如: https://github.com/minimal-manifest-twrp/platform_manifest_twrp_aosp): " repo_url
read -p "请输入分支名称 (例如: twrp-12.1): " branch_name

# 如果用户留空则提供默认值
if [ -z "$repo_url" ]; then
  repo_url="https://github.com/minimal-manifest-twrp/platform_manifest_twrp_aosp"
  echo "使用默认仓库地址: $repo_url"
fi

if [ -z "$branch_name" ]; then
  branch_name="twrp-12.1"
  echo "使用默认分支: $branch_name"
fi

echo "你选择的配置:"
echo "仓库地址: $repo_url"
echo "分支名称: $branch_name"

echo "=== 安装依赖包 ==="
sudo apt update
sudo apt install -y git-core gnupg flex bison build-essential zip curl \
zlib1g-dev gcc-multilib g++-multilib libc6-dev-i386 lib32ncurses5-dev \
x11proto-core-dev libx11-dev lib32z1-dev libgl1-mesa-dev libxml2-utils \
xsltproc unzip fontconfig libncurses5 libncurses5-dev python3 openjdk-8-jdk

echo "=== 配置 Git 用户信息 ==="
git config --global user.name "Rain Forever"
git config --global user.email "rainforever@example.com"

echo "=== 安装国内版 repo ==="
mkdir -p ~/bin
curl -o ~/bin/repo https://mirrors.tuna.tsinghua.edu.cn/git/git-repo
chmod +x ~/bin/repo
export REPO_URL=https://mirrors.tuna.tsinghua.edu.cn/git/git-repo
export PATH=$HOME/bin:$PATH
grep -qxF 'export REPO_URL=https://mirrors.tuna.tsinghua.edu.cn/git/git-repo' ~/.bashrc || echo 'export REPO_URL=https://mirrors.tuna.tsinghua.edu.cn/git/git-repo' >> ~/.bashrc
grep -qxF 'export PATH=$HOME/bin:$PATH' ~/.bashrc || echo 'export PATH=$HOME/bin:$PATH' >> ~/.bashrc

echo "=== 检查 repo 版本 ==="
repo version

echo "=== 创建源码目录并初始化 ==="
rm -rf ~/twrp
mkdir -p ~/twrp && cd ~/twrp

# 增加重试机制
echo "=== 初始化仓库 (最多重试3次) ==="
retry=0
max_retries=3
until repo init --depth=1 -u "$repo_url" -b "$branch_name"; do
  retry=$((retry + 1))
  if [ $retry -ge $max_retries ]; then
    echo "初始化仓库失败，超过最大重试次数"
    exit 1
  fi
  echo "重试第 $retry 次..."
  sleep 5
done

echo "=== 替换 Google 源为清华镜像 ==="
sed -i 's#https://android.googlesource.com#https://mirrors.tuna.tsinghua.edu.cn/git/AOSP#g' .repo/manifest.xml || true

echo "=== GitHub 加速 ==="
sed -i 's#https://github.com/#https://ghproxy.com/https://github.com/#g' .repo/manifest.xml || true

echo "=== 同步源码 ==="
repo sync -c --no-tags --no-clone-bundle -j$(nproc --all)

echo "✅ 完成！源码在 ~/twrp"
